#import the libraries
import pandas as pd
import numpy as np
s=pd.Series([67,45,23,6,12,57],index=["e","d","a","f","b","c"])
s
e 67 d 45 a 23 f 6 b 12 c 57 dtype: int64
s.sort_index()
a 23 b 12 c 57 d 45 e 67 f 6 dtype: int64
Sorting by value can be done by sort_value command.
s.sort_values()
f 6 b 12 a 23 d 45 c 57 e 67 dtype: int64
data = {'Name':pd.Series(['Akshay','Rajat','Robin','Kapil','James','Cyril']),'Age':pd.Series([25,26,29,27,23,21]),'Rating':pd.Series([4.23,2.35,1.56,3.20,4.62,3.99])}
df = pd.DataFrame(data,index=[5,3,2,4,1])
df
Name | Age | Rating | |
---|---|---|---|
5 | Cyril | 21 | 3.99 |
3 | Kapil | 27 | 3.20 |
2 | Robin | 29 | 1.56 |
4 | James | 23 | 4.62 |
1 | Rajat | 26 | 2.35 |
df.sort_index()
Name | Age | Rating | |
---|---|---|---|
1 | Rajat | 26 | 2.35 |
2 | Robin | 29 | 1.56 |
3 | Kapil | 27 | 3.20 |
4 | James | 23 | 4.62 |
5 | Cyril | 21 | 3.99 |
df.sort_index(axis=1)
Age | Name | Rating | |
---|---|---|---|
5 | 21 | Cyril | 3.99 |
3 | 27 | Kapil | 3.20 |
2 | 29 | Robin | 1.56 |
4 | 23 | James | 4.62 |
1 | 26 | Rajat | 2.35 |
By default, sorting is sorted in ascending order.But sorting can also be done in descending order, by using ascending = False.
df.sort_index(ascending=False)
Name | Age | Rating | |
---|---|---|---|
5 | Cyril | 21 | 3.99 |
4 | James | 23 | 4.62 |
3 | Kapil | 27 | 3.20 |
2 | Robin | 29 | 1.56 |
1 | Rajat | 26 | 2.35 |
df.sort_values(by="Age")
Name | Age | Rating | |
---|---|---|---|
5 | Cyril | 21 | 3.99 |
4 | James | 23 | 4.62 |
1 | Rajat | 26 | 2.35 |
3 | Kapil | 27 | 3.20 |
2 | Robin | 29 | 1.56 |
df.sort_values(by="Age",ascending=True)
Name | Age | Rating | |
---|---|---|---|
5 | Cyril | 21 | 3.99 |
4 | James | 23 | 4.62 |
1 | Rajat | 26 | 2.35 |
3 | Kapil | 27 | 3.20 |
2 | Robin | 29 | 1.56 |
df.sort_values(by="Age",ascending=False)
Name | Age | Rating | |
---|---|---|---|
2 | Robin | 29 | 1.56 |
3 | Kapil | 27 | 3.20 |
1 | Rajat | 26 | 2.35 |
4 | James | 23 | 4.62 |
5 | Cyril | 21 | 3.99 |